<?php

namespace app\controller\System;

use app\BaseController;
use app\model\OperationLog;
use think\Request;
use think\Response;

class LogController extends BaseController
{
    /**
     * 获取日志列表
     */
    public function index(Request $request)
    {
        $params = $request->get();
        
        $result = OperationLog::getLogList($params);
        
        return $this->success($result, '获取日志列表成功');
    }

    /**
     * 获取日志详情
     */
    public function show($id)
    {
        $log = OperationLog::find($id);
        if (!$log) {
            return $this->error('日志不存在', 404);
        }

        return $this->success($log, '获取日志详情成功');
    }

    /**
     * 获取日志统计
     */
    public function statistics()
    {
        $moduleStats = OperationLog::getModuleStats();
        $statusStats = OperationLog::getStatusStats();
        
        // 今日日志数量
        $todayCount = OperationLog::where('created_at', '>=', date('Y-m-d'))->count();
        
        // 本周日志数量
        $weekCount = OperationLog::where('created_at', '>=', date('Y-m-d', strtotime('-7 days')))->count();
        
        // 本月日志数量
        $monthCount = OperationLog::where('created_at', '>=', date('Y-m-01'))->count();

        return $this->success([
            'module_stats' => $moduleStats,
            'status_stats' => $statusStats,
            'today_count' => $todayCount,
            'week_count' => $weekCount,
            'month_count' => $monthCount
        ], '获取统计信息成功');
    }

    /**
     * 清理旧日志
     */
    public function clean(Request $request)
    {
        $days = $request->post('days', 30);
        
        if ($days < 7) {
            return $this->error('最少保留7天的日志', 400);
        }
        
        $deletedCount = OperationLog::cleanOldLogs($days);
        
        return $this->success(['deleted_count' => $deletedCount], "成功清理{$deletedCount}条旧日志");
    }

    /**
     * 导出日志
     */
    public function export(Request $request)
    {
        $params = $request->get();
        $params['limit'] = 10000; // 导出最多10000条
        
        $result = OperationLog::getLogList($params);
        
        // 生成CSV文件
        $filename = 'operation_logs_' . date('Y-m-d_H-i-s') . '.csv';
        $filepath = runtime_path() . 'export/' . $filename;
        
        // 确保目录存在
        if (!is_dir(dirname($filepath))) {
            mkdir(dirname($filepath), 0755, true);
        }
        
        $fp = fopen($filepath, 'w');
        
        // 写入表头
        fputcsv($fp, [
            'ID', '用户ID', '用户名', '操作', '模块', '描述', '请求方法', 
            '请求URL', '请求参数', '响应码', '响应消息', 'IP地址', 
            '用户代理', '执行时间(秒)', '状态', '创建时间'
        ]);
        
        // 写入数据
        foreach ($result['list'] as $log) {
            fputcsv($fp, [
                $log['id'],
                $log['user_id'],
                $log['username'],
                $log['action'],
                $log['module'],
                $log['description'],
                $log['request_method'],
                $log['request_url'],
                $log['request_params'],
                $log['response_code'],
                $log['response_message'],
                $log['ip_address'],
                $log['user_agent'],
                $log['execution_time'],
                $log['status'],
                $log['created_at']
            ]);
        }
        
        fclose($fp);
        
        return $this->success([
            'download_url' => '/export/' . $filename
        ], '日志导出成功');
    }

    /**
     * 获取模块列表（用于筛选）
     */
    public function modules()
    {
        $modules = OperationLog::field('module')
            ->group('module')
            ->column('module');
        
        return $this->success($modules, '获取模块列表成功');
    }

    /**
     * 获取状态列表（用于筛选）
     */
    public function statuses()
    {
        $statuses = ['success', 'error', 'warning'];
        
        return $this->success($statuses, '获取状态列表成功');
    }
} 